// 常量定义
const TARGET_BASE_URL = 'https://generativelanguage.googleapis.com';
const TIMEOUT_MS = 10000; // 10秒超时
const MAX_RETRY_ATTEMPTS = 2;
const DEFAULT_USER_AGENT = 'Cloudflare-Workers-Proxy/1.0';

// 主事件监听器
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

// 处理请求
async function handleRequest(request) {
  if (request.method === 'OPTIONS') return handleOptions();
  if (request.method !== 'POST') return errorResponse(405, '方法不支持', '仅支持 POST 请求');

  const url = new URL(request.url);
  const apiKey = getApiKey(request, url);
  if (!apiKey) return errorResponse(401, '未授权', '需要通过 ?key= 或 x-goog-api-key 头提供 API Key');

  const targetUrl = buildTargetUrl(url, apiKey);
  if (!targetUrl) return errorResponse(400, '请求无效', '无法构造目标 URL');

  try {
    const response = await forwardRequest(targetUrl, request);
    return addCorsHeaders(response);
  } catch (error) {
    return handleForwardError(error);
  }
}

// 获取 API Key
function getApiKey(request, url) {
  return url.searchParams.get('key') || request.headers.get('x-goog-api-key');
}

// 构造目标 URL
function buildTargetUrl(url, apiKey) {
  try {
    const query = new URLSearchParams(url.search);
    if (!query.has('key')) query.set('key', apiKey);
    return `${TARGET_BASE_URL}${url.pathname}${query.toString() ? '?' + query : ''}`;
  } catch (error) {
    return null;
  }
}

// 转发请求
async function forwardRequest(url, request) {
  const headers = prepareHeaders(request.headers);
  const modifiedRequest = new Request(url, {
    method: 'POST',
    headers,
    body: request.body,
    redirect: 'follow',
    signal: AbortSignal.timeout(TIMEOUT_MS),
  });

  let lastError;
  for (let attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) {
    try {
      const response = await fetch(modifiedRequest);
      if (!response.body) {
        throw new Error('Response body is null');
      }
      return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
      });
    } catch (error) {
      lastError = error;
      if (attempt < MAX_RETRY_ATTEMPTS - 1) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1))); // 指数退避
      }
    }
  }
  throw lastError;
}

// 准备请求头
function prepareHeaders(originalHeaders) {
  const headers = new Headers(originalHeaders);
  if (!headers.get('Content-Type')) headers.set('Content-Type', 'application/json');
  if (!headers.get('User-Agent')) headers.set('User-Agent', DEFAULT_USER_AGENT);
  return headers;
}

// 添加 CORS 头
function addCorsHeaders(response) {
  const headers = new Headers(response.headers);
  headers.set('Access-Control-Allow-Origin', '*');
  headers.set('Access-Control-Allow-Methods', 'POST, OPTIONS');
  headers.set('Access-Control-Allow-Headers', '*');
  return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
}

// 处理转发错误
function handleForwardError(error) {
  const details = error.message || '未知错误';
  if (error.name === 'TypeError' && details.includes('fetch')) {
    return errorResponse(503, '服务不可用', `无法连接到目标服务器: ${details}`);
  }
  return errorResponse(500, '内部服务器错误', `转发失败: ${details}`);
}

// 错误响应
function errorResponse(status, message, details = '') {
  return new Response(JSON.stringify({ error: message, details }, null, 2), {
    status,
    headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
  });
}

// 处理 OPTIONS 请求
function handleOptions() {
  return new Response(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Max-Age': '86400',
    },
  });
}
